package com.dc.bobaoge.project.v2.to.v3.business.core;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dc.bobaoge.base.entity.advertisement.po.Advertisement;
import com.dc.bobaoge.base.entity.advertisement.po.AdvertisementRelease;
import com.dc.bobaoge.base.mapper.advertisement.AdvertisementMapper;
import com.dc.bobaoge.base.mapper.advertisement.AdvertisementReleaseMapper;
import com.dc.bobaoge.common.base.entity.message.business.BaseMessageBusinessPo;
import com.dc.bobaoge.common.em.MessageTemplateEnum;
import com.dc.bobaoge.common.util.YearQuarterUtil;
import com.dc.bobaoge.project.base.core.constant.BaseInfoConstant;
import com.dc.bobaoge.project.base.core.mq.RabbitMqUtil;
import com.dc.bobaoge.project.base.core.now.mapper.CustomAdvertisementReleaseMapper;
import com.dc.bobaoge.project.base.core.old.entity.OldCoreAdvertisement;
import com.dc.bobaoge.project.base.core.old.entity.OldCoreAdvertisementTimeLog;
import com.dc.bobaoge.project.base.core.old.entity.OldCoreAdvertisementType;
import com.dc.bobaoge.project.base.core.old.mapper.OldCoreAdvertisementMapper;
import com.dc.bobaoge.project.base.core.old.mapper.OldCoreAdvertisementTimeLogMapper;
import com.dc.bobaoge.project.base.core.old.mapper.OldCoreAdvertisementTypeMapper;
import com.dc.bobaoge.project.base.core.util.AdvertisementCommonUtil;
import com.dc.bobaoge.project.base.core.util.MessageCommonUtil;
import com.own.business.sync.trigger.base.entity.SyncTrigger;
import com.own.business.sync.trigger.base.method.ResolveMethod;
import com.own.component.common.exception.BusinessSimpleException;
import com.own.component.common.util.list.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * AdvertisementResolveMethod
 *
 * @author chenxueli
 * @date 2023-12-22 11:00:00
 */
@Slf4j
@Component
public class AdvertisementResolveMethod implements ResolveMethod {

    @Resource
    private RabbitMqUtil rabbitMqUtil;

    @Resource
    private OldCoreAdvertisementMapper oldCoreAdvertisementMapper;
    @Resource
    private OldCoreAdvertisementTypeMapper oldCoreAdvertisementTypeMapper;
    @Resource
    private OldCoreAdvertisementTimeLogMapper oldCoreAdvertisementTimeLogMapper;

    @Resource
    private AdvertisementMapper advertisementMapper;
    @Resource
    private AdvertisementReleaseMapper advertisementReleaseMapper;

    @Resource
    private CustomAdvertisementReleaseMapper customAdvertisementReleaseMapper;

    @Resource
    private MessageCommonUtil messageCommonUtil;

    /**
     * 修改的处理方法
     *
     * @param trigger 日志信息
     */
    @Override
    public void update(SyncTrigger trigger) {
        // 查询广告的信息
        var oldCoreAdvertisement = oldCoreAdvertisementMapper.selectById(trigger.getTargetId());
        if (oldCoreAdvertisement == null) {
            throw new BusinessSimpleException("未查询到广告信息");
        }
        // 查询广告信息是否在新的数据库中存在
        var advertisement = advertisementMapper.selectById(oldCoreAdvertisement.getAdvmsgId());
        if (advertisement == null) {
            // 新增
            add(trigger, oldCoreAdvertisement);
            return;
        }
        // 处理广告主要的信息
        buildCommon(advertisement, oldCoreAdvertisement);
        var quarter = advertisement.getSharding();
        // 处理广告的媒资信息
        messageCommonUtil.updateImageAsset(oldCoreAdvertisement.getAdvmsgId(), MessageTemplateEnum.ADVERTISEMENT.getType(), quarter, oldCoreAdvertisement.getAdvmsgImages());
        // 处理广告的投放日期
        handleReleaseDate(oldCoreAdvertisement.getAdvmsgId(), advertisement);
        // 修改广告主信息
        advertisementMapper.updateById(advertisement);
        // 提交完成信息到消息队列
        rabbitMqUtil.syncMessage(advertisement.getId(), quarter, MessageTemplateEnum.ADVERTISEMENT.getType());
    }

    /**
     * 新增的处理方法
     *
     * @param trigger              日志信息
     * @param oldCoreAdvertisement 旧的广告信息
     */
    private void add(SyncTrigger trigger, OldCoreAdvertisement oldCoreAdvertisement) {
        var advertisement = buildCommon(new Advertisement(), oldCoreAdvertisement);
        // 新增过去的数据红包需要设置成0
        advertisement.setFkRedPacketId(0L);
        advertisement.setHasRedPacket(0);
        var quarter = advertisement.getSharding();
        // 保存广告主要信息
        advertisementMapper.insert(advertisement);
        // 处理广告的媒资信息
        messageCommonUtil.updateImageAsset(oldCoreAdvertisement.getAdvmsgId(), MessageTemplateEnum.ADVERTISEMENT.getType(), quarter, oldCoreAdvertisement.getAdvmsgImages());
        // 处理广告的投放日期
        handleReleaseDate(oldCoreAdvertisement.getAdvmsgId(), advertisement);
        // 提交完成信息到消息队列
        rabbitMqUtil.syncMessage(advertisement.getId(), quarter, MessageTemplateEnum.ADVERTISEMENT.getType());
    }

    /**
     * 设置广告的公共信息
     *
     * @param advertisement        广告信息
     * @param oldCoreAdvertisement 旧的广告信息
     * @return 广告信息
     */
    private Advertisement buildCommon(Advertisement advertisement, OldCoreAdvertisement oldCoreAdvertisement) {
        var quarter = YearQuarterUtil.get(oldCoreAdvertisement.getAdvmsgDate());

        advertisement.setId(oldCoreAdvertisement.getAdvmsgId());
        advertisement.setSharding(quarter);
        advertisement.setFkChargeModeId(oldCoreAdvertisement.getAdvmsgCostId());
        advertisement.setRkChargeModeName(oldCoreAdvertisement.getAdvmsgCost());
        advertisement.setPlacement(getPlacement(oldCoreAdvertisement.getAdvmsgTypeId()));
        advertisement.setFkUserId(oldCoreAdvertisement.getAdvmsgUserId());
        var channel = AdvertisementCommonUtil.DefaultChannel.getChannelByMoldId(oldCoreAdvertisement.getAdvmsgMoldId());
        if (channel == null) {
            throw new BusinessSimpleException("未查询到投放的频道信息");
        }
        advertisement.setFkChannelId(channel.getChannelId());
        advertisement.setRfChannelName(channel.getChannelName());
        advertisement.setFkZoneId(0L);
        advertisement.setRfZoneName("全国商圈");
        // 设置联系信息
        advertisement.setRfContactPhone(oldCoreAdvertisement.getAdvmsgUserPhone());
        advertisement.setFkContactUserId(oldCoreAdvertisement.getAdvmsgUserId());

        advertisement.setContent(oldCoreAdvertisement.getAdvmsgContent());
        advertisement.setPublishTime(oldCoreAdvertisement.getAdvmsgDate());
        advertisement.setAddress(oldCoreAdvertisement.getAdvmsgAddress());
        // 设置广告主图片
        if (StringUtils.isNotBlank(oldCoreAdvertisement.getAdvmsgMaster())) {
            var list = ListUtil.Spilt.to(oldCoreAdvertisement.getAdvmsgMaster(), BaseInfoConstant.IMAGE_SPILT);
            advertisement.setImageHorizontalUrl(list.isEmpty() ? "" : list.getFirst());
            advertisement.setImageVerticalUrl("");
        }
        // 拒绝理由
        advertisement.setAuditRemark(oldCoreAdvertisement.getAdvmsgRefuseReson());
        // 设置广告的位置序号信息
        advertisement.setPlacementSequence(getPlacementSequence(oldCoreAdvertisement.getAdvmsgSeatId()));
        // 设置广告的审核状态
        buildAuditStatus(advertisement, oldCoreAdvertisement);
        return advertisement;
    }

    /**
     * 设置状态信息
     * <p>
     * 旧广告状态 0=审核中 1=正在进行 2=手动结束投放 3=管理员拒绝 4=管理员删除 5=已结束 6=未开始 7=不是购买当天的广告 9=没支付
     * <p>
     * 新广告状态 1=待审核 2=审核通过 3=审核不通过 4=完成 5=已违规 6=锁定 7=待支付 8=管理员下架 9=用户下架
     *
     * @param advertisement        广告信息
     * @param oldCoreAdvertisement 旧的广告信息
     */
    private void buildAuditStatus(Advertisement advertisement, OldCoreAdvertisement oldCoreAdvertisement) {
        switch (oldCoreAdvertisement.getAdvmsgState()) {
            case 1, 6:
                advertisement.setAuditStatus(BaseMessageBusinessPo.AuditStatus.PASS);
                advertisement.setAuditTime(oldCoreAdvertisement.getAdvmsgVerifyDate());
                break;
            case 7:
                advertisement.setAuditStatus(BaseMessageBusinessPo.AuditStatus.WAIT);
                break;
            case 2, 5:
                if (advertisement.getAuditStatus() == BaseMessageBusinessPo.AuditStatus.USER_UN_SHELVE) {
                    advertisement.setAuditTime(oldCoreAdvertisement.getAdvmsgVerifyDate());
                } else {
                    advertisement.setAuditStatus(BaseMessageBusinessPo.AuditStatus.ADMIN_UN_SHELVE);
                    advertisement.setAuditTime(oldCoreAdvertisement.getAdvmsgVerifyDate());
                }
                break;
            case 3:
                advertisement.setAuditStatus(3);
                advertisement.setAuditTime(oldCoreAdvertisement.getAdvmsgVerifyDate());
                break;
            case 4:
                advertisement.setAuditStatus(5);
                advertisement.setAuditTime(oldCoreAdvertisement.getAdvmsgVerifyDate());
                break;
            case 9:
                advertisement.setAuditStatus(7);
                break;
            case 0:
            default:
                advertisement.setAuditStatus(1);
                break;
        }
    }

    /**
     * 处理广告的投放日期信息
     *
     * @param advertisementId 广告id
     * @param advertisement   广告信息
     */
    private void handleReleaseDate(Long advertisementId, Advertisement advertisement) {
        // 删除已有的投放日期
        customAdvertisementReleaseMapper.delete(advertisementId);
        // 查询广告的投放日期
        var wrapper = new LambdaQueryWrapper<OldCoreAdvertisementTimeLog>().eq(OldCoreAdvertisementTimeLog::getLogAdvId, advertisementId);
        var timeLogList = oldCoreAdvertisementTimeLogMapper.selectList(wrapper);
        var releaseList = timeLogList.stream().map(item -> {
            var release = new AdvertisementRelease();
            release.setStatus(1);
            release.setFkAdvertisementId(item.getLogAdvId());
            release.setReleaseDate(item.getLogDate().toLocalDate());
            release.setPublishTime(item.getLogTime());
            release.setFkZoneId(0L);
            release.setFkChannelId(advertisement.getFkChannelId());
            release.setQuarter(advertisement.getSharding());
            release.setPlacement(advertisement.getPlacement());
            release.setPlacementSequence(advertisement.getPlacementSequence());
            return release;
        }).collect(Collectors.toList());
        // 保存
        advertisementReleaseMapper.insertBatch(releaseList);
    }

    /**
     * 获取广告的位置信息（轮播广告还是消息广告）
     * <p>
     * 广告类型 1是轮播，23是消息广告
     *
     * @param typeId 广告类型
     * @return 位置信息
     */
    public Integer getPlacement(Integer typeId) {
        return typeId != null && typeId == 1 ? 1 : 2;
    }

    /**
     * 获取广告的位置序号信息
     *
     * @param seatId 位置id
     * @return 位置序号
     */
    public Integer getPlacementSequence(Integer seatId) {
        var wrapper = new LambdaQueryWrapper<OldCoreAdvertisementType>().eq(OldCoreAdvertisementType::getTypesubId, seatId).last("limit 1");
        var typeSub = oldCoreAdvertisementTypeMapper.selectOne(wrapper);
        return typeSub == null ? 0 : typeSub.getTypesubNumber() - 1;
    }

    /**
     * 名称信息
     *
     * @return 名称
     */
    @Override
    public String name() {
        return "advertisement";
    }

}
